package cn.gov.mwr.sl651.body;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.gov.mwr.sl651.AbstractBody;
import cn.gov.mwr.sl651.utils.ByteUtil;

/**
 * 
 * 测试报(6.6.4.3),功能码：30H
 * 
 * @ClassName: Up30Body
 * @Description: 测试报，上行报文结构
 * @author lipujun
 * @date Feb 20, 2013
 * 
 */
public class Up42Body extends UpBaseBody implements Serializable {

	/**
	 * 1、流水号
	 * 
	 * 取值范围：2字节HEX码，范围1～65535
	 */
	// public int serialId;

	/**
	 * 2、发报时间
	 */
	// public String sendDate;

	/**
	 * 3、遥测站地址
	 */

	/**
	 * 6、观测要素
	 */
	public List<DataItem> items = null;// new ArrayList<DataItem>();

	public void setItems(List<DataItem> items) {
		this.items = items;
	}

	public List<DataItem> getItems() {
		return items;
	}
	
	public void addItem(DataItem item) {
		if (items == null) {
			items = new ArrayList<DataItem>();
		}
		items.add(item);
	}
	
	@Override
	public byte[] getContent() {
		// TODO Auto-generated method stub
		if (this.content != null)
			return content;

		int total = getLength();
		content = new byte[total];

		System.arraycopy(ByteUtil.ushortToBytes(serialId), 0, content, 0, 2);

		// 转换为6字节的BCD码
		System.arraycopy(ByteUtil.str2Bcd(sendDate), 0, content, 2, 6);

		// 遥测站地址标识符
		System.arraycopy(stationAddrSymbol, 0, content, 8, 2);

		// 遥测站地址，转换为5字节的BCD码
		System.arraycopy(ByteUtil.str2Bcd(stcd), 0, content, 10, 5);
		
		int pos = 8 + 7 ;
		
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				DataItem item = (DataItem) (items.get(i));
				if (item != null) {
					System.arraycopy(item.getLabel(), 0, content, pos, item
							.getLabel().length);
					pos = pos + item.getLabel().length;
					System.arraycopy(item.getValue(), 0, content, pos, item
							.getValue().length);
					pos = pos + item.getValue().length;
				}
			}
		}
		return content;
	}

	public int getLength() {
		int pos = 0;
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				DataItem item = (DataItem) (items.get(i));
				pos = pos + item.getLabel().length + item.getValue().length;
			}
		}

		return 8 + 7 + pos;
	}

}
